package cn.fl.bizflow.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lionbridge.activiti.constant.EnumInterface.TaskStatus;

import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.bizflow.condition.RskUsrAchLogQC;
import cn.fl.bizflow.constant.RskUsrAchLogConstant;
import cn.fl.bizflow.service.IRskUsrAchLogService;
import cn.fl.bizflow.utils.ImportMyAchienementsList;
import cn.fl.bizflow.vo.RskUsrAchLogVO;
import cn.fl.flow.vo.FlowMyTaskVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.system.vo.SysUsrVO;
import fl.flow.facade.flow.condition.FlowQueryCondition;

/**
 * @Description: 用户提成记录表 控制层
 */
@Controller
@RequestMapping("/bizflow/rskUsrAchLog")
public class RskUsrAchLogController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(RskUsrAchLogController.class);
	/**
	 * RskUsrAchLog 服务层BEAN
	 */
	@Autowired
	private IRskUsrAchLogService rskUsrAchLogService;
	/**
	 * 文件上传记录服务
	 */
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;
    
    @Autowired
    private ISysUsrService iSysUsrService;
    

	/**
	 * 到我的任务--绩效列表页面
	 */
	@RequestMapping(value = "/toMyTaskAchievementsPage.do", method = { RequestMethod.GET})
	public ModelAndView toMyTaskDBPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("bizflow/rskusrach/myAchievements");

		return view;
	}
	
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String usrNm = request.getParameter("usrNm");
		String usrCd = request.getParameter("usrCd");
		String achMthSart = request.getParameter("achMthSart");
		String achMthEnd = request.getParameter("achMthEnd");
		String achPayMthStart = request.getParameter("achPayMthStart");
		String achPayMthEnd = request.getParameter("achPayMthEnd");
		
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		RskUsrAchLogQC qc = new RskUsrAchLogQC();
		if (StringUtils.isNotEmpty(usrNm)) {
			qc.setUsrNm(usrNm);
		}
		if (StringUtils.isNotEmpty(usrCd)) {
			qc.setUsrCd(usrCd);
		}
		if (StringUtils.isNotEmpty(achMthSart)) {
			qc.setAchMthSart(achMthSart);
		}
		if (StringUtils.isNotEmpty(achMthEnd)) {
			qc.setAchMthEnd(achMthEnd);
		}
		if (StringUtils.isNotEmpty(achPayMthStart)) {
			qc.setAchPayMthStart(achPayMthStart);
		}
		if (StringUtils.isNotEmpty(achPayMthEnd)) {
			qc.setAchPayMthEnd(achPayMthEnd);
		}
	   /* if(CurrentThreadContext.getCurrentOrgCd().contains(RskUsrAchLogConstant.CODE_RSK_USR_ACH_LOG_FILE_ORG_CD)){
	    	qc.setIsNO("1"); //1是0否
		  }
		qc.setIngorgcd(CurrentThreadContext.getCurrentOrgCd());	 //当前组织架构 */		
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setCurrUsrId(CurrentThreadContext.getCurrentUserId());
		qc.setOpUsrId(CurrentThreadContext.getCurrentUserId());
		SysUsrVO selectById = this.iSysUsrService.selectById(CurrentThreadContext.getCurrentUserId(), CurrentThreadContext.getCurrentSysCd());
		qc.setCurrUsrNm(selectById.getUsrNm());
		
		//向下匹配规则
		if(CurrentThreadContext.getCurrentOrgCd().contains(RskUsrAchLogConstant.CODE_RSK_USR_ACH_LOG_FILE_ORG_CD)){
		  //如果是人力资源 就查询所有数据	
	     qc.setIsAuth(false);
		}else{
		//加入数据权限
		qc.setIsAuth(true);
		}
		page.setCondition(qc);
		page = this.rskUsrAchLogService.searchListPage(page);
		
		List<RskUsrAchLogVO> list = (List<RskUsrAchLogVO>) page.getResultList();
		ListPageVO<RskUsrAchLogVO> listPage = new ListPageVO<RskUsrAchLogVO>(list, page.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	
	 /**
	  * 到绩效导入页面
	  */
    @RequestMapping(value = "/toAchievementsImportPage.do", method = {RequestMethod.GET})
    public ModelAndView toFundImportPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toFundImportPage", "加载toFundImportPage资金导入列表面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("bizflow/rskusrach/myAchievementsImportList");
        String fileNm = request.getParameter("fileNm");
        String filePath = request.getParameter("filePath");//文件路径
        mav.addObject("filePath", filePath);
        mav.addObject("fileNm", fileNm);
        List<RskUsrAchLogVO> list = ImportMyAchienementsList.importXls(filePath);
        if (CollectionUtils.isNotEmpty(list)) {
            mav.addObject("fundList", JSON.toJSONString(list));
            mav.addObject("success", "true");//导入绩效数据验证通过
            for (RskUsrAchLogVO vo : list) {
                if ("1".equals(vo.getAstart())) {//验证数据状态是否通过（1不通过 0通过）
                    mav.addObject("success", "false");//导入绩效数据验证不通过
                    break;
                }
            }
        } else {
            mav.addObject("success", "false");//无导入绩效数据
        }
        return mav;
    }
    
    /**
     * 绩效导入 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importAchievements.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO importFund(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "绩效导入成功");
        String filePath = request.getParameter("filePath");//文件路径
        String fileNm = request.getParameter("fileNm");
    	String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);
        List<RskUsrAchLogVO> list = ImportMyAchienementsList.importXls(filePath);
        if (CollectionUtils.isNotEmpty(list)) {
        	SysUlFilesRecVO  fileRec=new SysUlFilesRecVO();
        	fileRec.setFileNm(fileNm);//文件名
			fileRec.setFilePath(filePath);//文件路径
			fileRec.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
			fileRec.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//组织架构代码
			//上传资料明细（SYS_UL_DAT_CFG_DTL）
			fileRec.setCfgCd(RskUsrAchLogConstant.CODE_RSK_USR_ACH_LOG_FILE_CD);//配置编号（RSK001）
			fileRec.setDatNm(RskUsrAchLogConstant.CODE_RSK_USR_ACH_LOG_FILE_NM);// 配置项名称
			fileRec.setCfgDtlCd(RskUsrAchLogConstant.CODE_RSK_USR_ACH_LOG_FILE_CD_ACH);// 上传配置明细表配置子编号
			fileRec.setTabNm("RSK_USR_ACH_LOG");//数据表名
			fileRec.setFileRem(CurrentThreadContext.getCurrentUserName());//取得当前人
			fileRec.setCrtTm(new Date());//创建时间
			fileRec.setCrtUsrId(CurrentThreadContext.getCurrentUserId());//创建人
			fileRec.setMdfTm(new Date());//更新时间
			fileRec.setMdfUsrId(CurrentThreadContext.getCurrentUserId());//更新人
			fileRec.setIsDel(BaseConstant.IS_YESNO_NO);//是否删除（1：是，0：否）
			fileRec.setAbsLocPath(rootPath+filePath);
        	Long id = this.sysUlFilesRecService.add(fileRec);
        	
            for (RskUsrAchLogVO vo : list) {
            	vo.setUlRecId(id);
            	vo.setIsDel(0);
            	vo.setCrtTm(new Date());
            	vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            	Long  convertYuanToFen= DecimalUtils.convertYuanToFen(Double.parseDouble(vo.getAchAmt()));
            	vo.setAchAmt(String.valueOf(convertYuanToFen));
            	Long  realAchAmt= DecimalUtils.convertYuanToFen(Double.parseDouble(vo.getRealAchAmt()));
            	vo.setRealAchAmt(String.valueOf(realAchAmt));
            }
            boolean flag = this.rskUsrAchLogService.add(list);//多条插入
            if (!flag) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.info(logger, "importAchievements", "资金导入失败.DATA:" + filePath, CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "importAchievements", "资金导入成功.DATA:" + filePath, CurrentThreadContext.getCurrentUserName());
        } else {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "importAchievements", "资金导入失败.导入数据为空", CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }
    

     /***
      * 历史页面 （仅人力资源）
      * @param request
      * @param response
      * @return
      */
	@RequestMapping(value = "/toMyAchievementsPage.do", method = { RequestMethod.GET})
	public ModelAndView toMyTaskGQPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("bizflow/rskusrach/myAchievementslS");
	
		
		
		return view;
	}
	
	

	/**
	 * 初始化挂起列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initMyAchievementslSList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initMyTaskGQList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		
		String crtTmstart = request.getParameter("crtTmstart");
		String crtTmend = request.getParameter("crtTmend");
		String fileNm = request.getParameter("fileNm");
		String isDel = request.getParameter("isDel");
		//String crtUsrRlNm = request.getParameter("crtUsrRlNm"); ?
		
		
		SysUlFilesRecQueryCondition qc=new SysUlFilesRecQueryCondition();
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));//每页显示100条
		}
		
		if (StringUtils.isNotEmpty(crtTmstart)) {
			qc.setCrtTmstart(DateUtils.formatStringToDate(crtTmstart, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmend)) {
			qc.setCrtTmend(DateUtils.formatStringToDate(crtTmend, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(fileNm)) {
			qc.setFileNm(fileNm);
		}
		if (StringUtils.isNotEmpty(isDel)) {
			qc.setIsDel(Integer.valueOf(isDel));
		}
		
		qc.setCfgCd("RSK001");
		qc.setIsExists("1");
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//取得当前系统代码
		page.setCondition(qc);
		
		Pager pager = this.sysUlFilesRecService.searchListPage(page);
		
		List<SysUlFilesRecVO> list = (List<SysUlFilesRecVO>) pager.getResultList();
	
		ListPageVO<SysUlFilesRecVO> listPage = new ListPageVO<SysUlFilesRecVO>(list, pager.getTotalCount());
		return listPage;
	}
	

	
	
	@RequestMapping(value = "/modifyStart.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object modifyStart(HttpServletRequest request, HttpServletResponse response) {
		String files_id = request.getParameter("files_id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(files_id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("ID不能为空！");
			return result;
		}
		try {
			SysUlFilesRecVO entity =new SysUlFilesRecVO();
			entity.setId(Long.parseLong(files_id));
			entity.setIsDel(1);
			boolean modify = this.sysUlFilesRecService.modify(entity);
			if( modify == false){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("操作失败！");
			}else{
				
				boolean removeById = this.rskUsrAchLogService.removeById(Long.parseLong(files_id));	
				if(removeById== false){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("操作提成记录失败！"+files_id);
				}
			}

		} catch (BaseException e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(e.getMessage());
			BaseLogUtils.info(logger, "modifyFlowRecover", "业务异常:" + e.getMessage());
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误！");
			BaseLogUtils.error(logger, "modifyFlowRecover", "系统错误", e);
		}
		return result;
	}
	

}

